import { HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateSortDto } from './dto/create-sort.dto';
import { UpdateSortDto } from './dto/update-sort.dto';
import { Sort } from './sorts.entity';

@Injectable()
export class SortsService {
  constructor(
    @InjectRepository(Sort)
    private sortsService: Repository<Sort>,
  ) {}

  async create(createSortDto: CreateSortDto) {
    const { sortName } = createSortDto;
    const sort = await this.sortsService.findOne({ sortName });
    if (sort) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: '分类名已存在！',
      };
    }
    return this.sortsService
      .save(createSortDto)
      .then(() => {
        return {
          code: HttpStatus.OK,
          message: '创建成功!',
        };
      })
      .catch((error) => {
        return {
          code: HttpStatus.INTERNAL_SERVER_ERROR,
          message: error.message,
        };
      });
  }

  async findAll() {
    const data = await this.sortsService.find();
    return {
      code: HttpStatus.OK,
      data,
    };
  }

  findOne(id: number) {
    return `This action returns a #${id} sort`;
  }

  async update(id: number, updateSortDto: UpdateSortDto) {
    const sort = await this.sortsService.findOne(id);
    if (!sort) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: '该分类不存在',
      };
    }
    const { sortName } = updateSortDto;
    sort.sortName = sortName;
    return this.sortsService
      .save(sort)
      .then(() => {
        return {
          code: HttpStatus.OK,
          message: '修改成功！',
        };
      })
      .catch((error) => {
        return {
          code: HttpStatus.INTERNAL_SERVER_ERROR,
          message: error.message,
        };
      });
  }

  async remove(id: number) {
    const sort = await this.sortsService.findOne(id);
    if (!sort) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: '该分类不存在！',
      };
    }
    return this.sortsService
      .remove(sort)
      .then(() => {
        return {
          code: HttpStatus.OK,
          message: '删除成功!',
        };
      })
      .catch((error) => {
        return {
          code: HttpStatus.INTERNAL_SERVER_ERROR,
          message: error.message,
        };
      });
  }
}
